package application

import (
	"errors"
	"gitee.com/dh114007/wechat_token/config"
	"gitee.com/dh114007/wechat_token/core/httputils"
	"net/http"
)

func (a *App) getAccessToken(w http.ResponseWriter, r *http.Request) {
	var err error
	defer func() {
		if err != nil {
			httputils.ResponseWithError(w, err)
		}
	}()
	var params struct {
		AppID string `json:"appid"`
	}
	err = httputils.ReadJSON(r, &params)
	if err != nil {
		err = &httputils.HttpStatusError{
			Code: http.StatusNotFound,
			Err:  errors.New("appid not exits"),
		}
		return
	}

	tokenRet, err := requestAccessToken(params.AppID)
	if err != nil {
		return
	}

	httputils.ResponseWithJSON(w, http.StatusOK, "Success", tokenRet)
}

func (a *App) getJsApiTicket(w http.ResponseWriter, r *http.Request) {
	var err error
	defer func() {
		if err != nil {
			httputils.ResponseWithError(w, err)
		}
	}()
	var params struct {
		AppID string `json:"appid"`
	}
	err = httputils.ReadJSON(r, &params)
	if err != nil {
		err = &httputils.HttpStatusError{
			Code: http.StatusNotFound,
			Err:  errors.New("appid not exits"),
		}
		return
	}
	ticketRet, err := requestJsApiTicket(params.AppID)
	if err != nil {
		return
	}
	httputils.ResponseWithJSON(w, http.StatusOK, "Success", ticketRet)
}

func (a *App) getAppSecret(w http.ResponseWriter, r *http.Request) {
	var err error
	defer func() {
		if err != nil {
			httputils.ResponseWithError(w, err)
		}
	}()
	var params struct {
		AppID string `json:"appid"`
	}
	err = httputils.ReadJSON(r, &params)
	if err != nil {
		err = &httputils.HttpStatusError{
			Code: http.StatusNotFound,
			Err:  errors.New("appid not exits"),
		}
		return
	}
	secret, ok := config.Conf.Wechat.Keys[params.AppID]
	if ok == false {
		err = &httputils.HttpStatusError{
			Code: http.StatusForbidden,
			Err:  errors.New("appid not exits"),
		}
		return
	}
	httputils.ResponseWithJSON(w, http.StatusOK, "Success", &WeixinSecretRet{
		Secret: secret,
	})
}

func (a *App) getJSCode2Session(w http.ResponseWriter, r *http.Request) {
	var err error
	defer func() {
		if err != nil {
			httputils.ResponseWithError(w, err)
		}
	}()

	var params struct {
		AppID string `json:"appid"`
		Code  string `json:"code"`
	}
	err = httputils.ReadJSON(r, &params)
	if err != nil {
		err = &httputils.HttpStatusError{
			Code: http.StatusNotFound,
			Err:  errors.New("appid not exits"),
		}
		return
	}
	WeixinJSCode2SessionRet, err := requestJSCode2Session(params.AppID, params.Code)
	if err != nil {
		return
	}
	httputils.ResponseWithJSON(w, http.StatusOK, "Success", WeixinJSCode2SessionRet)
}